package com.jeesite.modules.stock.service;

import com.jeesite.common.lang.DateUtils;
import com.jeesite.common.utils.SpringUtils;
import com.jeesite.modules.stock.dao.UserRequestLogsDao;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class RequestLimitCache {

    static int firstLimitHour = 1;
    static int secondLimitHour = 3;

    public static Map<String, List<Long>> requestLimitCache = new ConcurrentHashMap<>();

    public static synchronized void addLimit(String userId) {
        List<Long> list = requestLimitCache.computeIfAbsent(userId, key -> new ArrayList<>());
        if (!list.isEmpty()) {
            Long first = list.getFirst();
            String d1 = DateUtils.formatDate(new Date(first));
            String d2 = DateUtils.formatDate(new Date());
            if (!d1.equals(d2)) {
                list.clear();
            }
        }
        if (list.isEmpty()) {
            // 第一次限制1小时的使用
            list.addFirst(System.currentTimeMillis() + (long) firstLimitHour * 3600 * 1000);
        } else {
            //第二次则限制3小时
            list.addFirst(System.currentTimeMillis() + (long) secondLimitHour * 3600 * 1000);
        }
    }

    private static String tipTime(int hour, float remainHour) {
        String tipTime = "";
        if (hour > 0) {
            tipTime += hour + "小时";
        }
        if (remainHour > 0) {
            int minute = (int) (remainHour * 60);
            tipTime += minute + "分钟";
        }
        if (hour == 0 && remainHour == 0) {
            tipTime = "稍";
        }
        return tipTime;
    }

    public static synchronized String getLimitTip(String userId) {
        if (userId == null || "null".equalsIgnoreCase(userId) || "".equalsIgnoreCase(userId)) {
            return null;
        }
        if (!requestLimitCache.containsKey(userId))
            return null;
        List<Long> list = requestLimitCache.get(userId);
        if (list.isEmpty()) {
            return null;
        }
        Long first = list.getFirst();
        long now = System.currentTimeMillis();

        if (now < first) {
            float afterTime = BigDecimal.valueOf((first - now) / 1000.0 / 60.0 / 60.0)
                    .setScale(2, RoundingMode.HALF_UP).floatValue();
            int hour = (int) afterTime;
            float remainHour = afterTime - hour;
            return "请求太过频繁，请" + tipTime(hour, remainHour) + "后再访问";
        } else {
            UserRequestLogsDao bean = SpringUtils.getBean(UserRequestLogsDao.class);
            bean.updateValid(userId, new Date(first), 0);
        }
        return null;
    }
}
